document.addEventListener('DOMContentLoaded', () => {
    const postForm = document.getElementById('postForm');
    const coverPreview = document.getElementById('coverPreview');
    const coverInput = document.getElementById('cover');
    const previewImage = document.getElementById('previewImage');
    const submitBtn = document.querySelector('button[type="submit"]');
    let selectedFile = null;

    // 初始化编辑器
    const easyMDE = new EasyMDE({
        element: document.getElementById('markdown-editor'),
        spellChecker: false,
        placeholder: "Enjoy Markdown! coding now...",
        autofocus: true,
        toolbar: [
            'bold', 'italic', 'heading', '|',
            'quote', 'code', 'unordered-list', 'ordered-list', '|',
            'link', 'image', '|',
            'preview', 'side-by-side', 'fullscreen', '|',
            'guide'
        ],
        renderingConfig: {
            singleLineBreaks: false,
            codeSyntaxHighlighting: true,
            hljs: hljs,
            markedOptions: {
                highlight: function (code, language) {
                    if (language && hljs.getLanguage(language)) {
                        try {
                            return hljs.highlight(code, {
                                language: language
                            }).value;
                        } catch (e) { }
                    }
                    return code;
                }
            }
        },
        previewRender: function (plainText) {
            const preview = this.parent.markdown(plainText);
            setTimeout(() => {
                document.querySelectorAll('.editor-preview pre code').forEach((block) => {
                    hljs.highlightBlock(block);
                });
            }, 0);
            return preview;
        },
        status: false
    });

    hljs.highlightAll();

    coverPreview.addEventListener('click', () => {
        coverInput.click();
    });


    coverInput.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) {
            if (file.size > 20 * 1024 * 1024) {
                Swal.fire({
                    icon: 'warning',
                    title: '提示',
                    text: '文件大小不能超过 20MB',
                    confirmButtonColor: '#546d9e'
                });
                coverInput.value = '';
                return;
            }
            selectedFile = file;
            const reader = new FileReader();

            reader.onload = (e) => {
                previewImage.src = e.target.result;
                previewImage.style.display = 'block';
                document.querySelector('.upload-icon').style.display = 'none';
            };

            reader.readAsDataURL(file);
        }
    });

    postForm.addEventListener('submit', async (e) => {
        e.preventDefault();

        const titleInput = document.getElementById('title');
        const content = easyMDE.value();

        if (!titleInput.value.trim() || !content.trim()) {
            Swal.fire({
                icon: 'warning',
                title: '提示',
                text: '标题或内容不能为空',
                confirmButtonColor: '#546d9e'
            });
            return;
        }

        submitBtn.disabled = true;
        try {
            const formData = new FormData();
            formData.append('title', titleInput.value.trim());
            formData.append('content', content);
            formData.append('status', 1);

            if (selectedFile) {
                formData.append('cover', selectedFile);
            }

            // 发送请求
            const response = await request.post('/post', formData);

            if (response.code === 200) {
                Swal.fire({
                    icon: 'success',
                    title: '发布成功',
                    showConfirmButton: false,
                    timer: 1500
                }).then(() => {
                    window.location.href = 'blog.html';
                });
            }
        } catch (error) {
            console.error('发布失败:', error);
            Swal.fire({
                icon: 'error',
                title: '发布失败',
                text: error.response?.data?.message || error.message || '请重试',
                confirmButtonColor: '#546d9e'
            });
        } finally {
            submitBtn.disabled = false;
        }
    });
});